package util.resources;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader {
    
    public XMLReader()
    {
    }

    public String[] readFile(String filename, String level) {

        String[] result = new String[2];
        try {
            File file = new File(filename);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName(level);

            for (int s = 0; s < nodeLst.getLength(); s++) {
                
                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) fstNode;
                    
                    result[0] = getTagValue("Background", eElement);
                    result[1] = getTagValue("Characters", eElement);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    private String getTagValue(String sTag, Element eElement){
        NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0); 
     
        return nValue.getNodeValue();    
     }
    
//    public static void main(String[] args)
//    {
//        XMLReader reader = new XMLReader();
//        reader.readFile("src/resources/Kitty.xml","Level1");
//        System.out.println("done");
//    }
}
